package com.lph.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lph.model.Files;
import com.lph.service.BaseServiceI;

@Controller
@RequestMapping("/fc")
public class FilesController {
	@Resource(name="filesService")
	private BaseServiceI<Files> fbsi;
	 
	@RequestMapping("/getImg.coc")
	public void getImgeFile(HttpServletRequest req,HttpServletResponse res){
		String tname=req.getParameter("tname");
		String tid=req.getParameter("tid");
		Files f=new Files();
		f.setTid(Integer.parseInt(tid==null?"0":tid));
		f.setTname(tname);
		f=fbsi.get(f);
		//获取工程绝对路径
		String realPath=req.getSession().getServletContext().getRealPath("/");
		String path=realPath+"img/i07.png";
		if(f!=null){
			path=f.getFilepath();
		}
		File imageFile=new File(path);
		
		if(imageFile.exists()){
			try {
				FileInputStream fis = new FileInputStream(imageFile);
				OutputStream os = res.getOutputStream();
				int i = 0;
				byte[] bs = new byte[1024];
				while((i=fis.read(bs))!=-1){
					os.write(bs, 0, i);
					os.flush();
				}
				os.close();
				fis.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	@RequestMapping("/downFile")
	public void downFile(HttpServletRequest req,HttpServletResponse res)
	{
		String fileName=req.getParameter("fileName");
		String path=req.getParameter("path");
		
		//响应编码格式
		res.setCharacterEncoding("utf-8");
		//防止文件是打开而不是下载
		res.setContentType("multipart/form-data");
		//设置下载的文件名称
				res.setHeader("Content-Disposition", "attachment;fileName="+fileName);
				try {
					//打开文件输入流对象
					InputStream is = new FileInputStream(path);
					//文件输出流
					OutputStream os = res.getOutputStream();
					//进行读写
					byte bs[] = new byte[1024];
					int i = 0;
					while((i=is.read(bs))!=-1){
						os.write(bs, 0, i);
					}
					
					os.close();
					is.close();
					
				} catch (Exception e) {
					e.printStackTrace();
				}
	}
}
